'use strict'

//改变工作目录，切换到__dirname所在目录
process.chdir(__dirname)

const titbit = require('titbit')
const fs = require('fs')
// 使用HTTP/1.1客户端
const {httpcli} = require('gohttp')

const token = require('titbit-token')

const pg = require('pg')
const dbconfig = require('./dbconfig.js')
const wxkey = require('./wxkey.js')

let tok = new token({
    // token有效期，单位是秒
    expires: 30,

    // 必须是32位字母数字
    key: '1rjn54nuidfn453jhb84hjui32kudvfo',

    // 必须是16位字母数字
    iv: '9df32kjbj456kjnr'
})

//初始化数据库连接,创建连接池
let psql = new pg.Pool(dbconfig)

try {
    fs.accessSync('./images')
} catch (err) {
    fs.mkdirSync('./images')
}

let cert_path = '/usr/local/share';

const app = new titbit({
    //开启调试模式，会输出错误信息
    debug: true,
    globalLog: true,
    cert: `${cert_path}/wx.116dajun.xyz.pem`,
    key: `${cert_path}/wx.116dajun.xyz.key`
})

/**---------------content路由-------------------- */
app.get('/content', async c => {
    let sqltext = 'SELECT id,title,update_time FROM content';
    let r = await psql.query(sqltext);

    c.send(r.rows);
})
app.post('/content', async c => {
    try {
        //c.body是我交的请求体数据
        let data = JSON.parse(c.body);
        let sqltext = 'INSERT INTO content'
            + '(id,detail,title,add_time,update_time)'
            + 'VALUES($1,$2,$3,$4,$5)'

        //随机数转成16进制字符串并去掉前两位，字符串作为ID
        let id = Math.random().toString(16).substring(2)
        //c.helper.makeId(16)随机生成16位的id
        let tm = Date.now()

        let r = await psql.query(sqltext, [
            id, data.detail, data.title, tm, tm
        ])

        if (r.rowCount === 0) {
            return c.status(500).send('failed')
        }

        c.send(id)
    } catch (err) {
        console.log(err)
        s.status(400).send('bad data')
    }
})
app.get('/content/:id', async c => {
    let id = c.param.id

    let sqltext = 'SELECT id,detail,title,update_time '
    +' FROM content WHERE id=$1';

    let r = await psql.query(sqltext,[ id ])

    if(r.rowCount===0){
        return c.status(404).send('not found');
    }

})

app.delete('/content/:id', async c => {
    let r = await psql.query(`DELETE FROM content WHERE id=$1`,[ c.params.id ])

    c.send({
        count: r.rowCount
    })
})

/**-------------content路由 -END------------------ */


//添加一个get请求,c就是context
app.get('/', async c => {
    c.send('ok')
})

app.get('/upload', async c => {
    //c.helper是助手函数模块，其中有对stream.pipe的封装
    //c.reply是响应对象，http/1.1中指向response，http/2中指向stream
    await c.helper.pipe('./upload.html', c.reply)
})

app.post('/upload', async c => {
    let f = c.getFile('file')

    if (!f) {
        return c.status(400).send('file not found')
    }

    //生成唯一文件名
    let fname = c.helper.makeName(f.filename)
    try {
        await c.moveFile(f, `./images/${fname}`)
        c.send(fname)
    } catch (err) {
        c.status(500).send('failed')
    }


})
// //JS无需加分号，谁用谁知道
// //有时也得加分号，括号开头很需要
// ;(async ()=>{

// })();
//“  :  ”表示这个路由是带参数的路由,冒号后是一个变化的量(自己定)，将来要替换为真实的值
app.get('/image/:name', async c => {
    let imgname = c.param.name

    try {
        await c.helper.pipe(`./images/${imgname}`, c.reply)
    } catch (e) {
        c.status(404).send('image not found')
    }
})

//加一个表示用户信息的路由
app.get('/user/:name/:age/:mobile', async c => {
    console.log(c.param);  //在后台输出
    c.send(c.param);  //在浏览器中实现
})

app.get('/mp-login/:code', async c=> {
    // c.send(c.param);

    let auth_url = `https://api.weixin.qq.com/sns/jscode2session`
    + `?appid=${wxkey.appid}`
    + `&secret=${wxkey.secret}`
    + `&js_code=${c.param.code}`
    + `&grant_type=authorization_code`

    let ret = await httpcli.get(auth_url)
                        .then(res => {
                            return res.json()
                        })

    c.send(tok.make(ret))
})

//监听·1234运行服务
app.run(2021)